package com.ayoka.parenting.ui.live.discussgroup;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import com.ayoka.parenting.Constants;
import com.ayoka.parenting.R;
import com.ayoka.parenting.adapter.DiscussGroupMemberAdapter;
import com.ayoka.parenting.bean.BasicUserInfoBean;
import com.ayoka.parenting.bean.DiscussGroupBean;
import com.ayoka.parenting.bean.DiscussGroupTempRoomBean;
import com.ayoka.parenting.bean.UserManager;
import com.ayoka.parenting.databinding.ActivityDiscussGroupBinding;
import com.ayoka.parenting.mvp.MVPBaseActivity;
import com.ayoka.parenting.ui.live.liveclassroom.LiveClassroomActivity;
import com.ayoka.parenting.widget.MyCountDownTextView;
import com.ayoka.parenting.widget.MyCountDownTimer;
import com.jincp.common.brvah.layoutmanager.MyLinearLayoutManager;
import com.jincp.common.permission.MPermission;
import com.jincp.common.permission.annotation.OnMPermissionDenied;
import com.jincp.common.permission.annotation.OnMPermissionGranted;
import com.jincp.common.permission.annotation.OnMPermissionNeverAskAgain;
import com.jincp.common.utils.MyLogger;
import com.jincp.common.utils.StatusBarUtils;
import com.jincp.common.utils.ToastUtil;
import com.jincp.image.load.ImageLoader;
import com.tencent.imsdk.TIMMessage;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.ticsdk.core.TICManager;
import com.tencent.trtc.TRTCCloudDef;

import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * @ProjectName: MVPPlugin.
 * @ClassName: DiscussGroupActivity.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/10/10 18:17.
 */
public class DiscussGroupActivity extends MVPBaseActivity<ActivityDiscussGroupBinding, DiscussGroupContract.View, DiscussGroupPresenter> implements
        DiscussGroupContract.View,
        TICManager.TICMessageListener,
        TICManager.TICEventListener,
        TICManager.TICIMStatusListener{

    private String[] permissionList = {Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    public static void start(Activity activity, int roomId, String scheduleId) {
        Intent intent = new Intent(activity, DiscussGroupActivity.class);
        intent.putExtra("ROOM_ID", roomId);
        intent.putExtra("SCHEDULE_ID", scheduleId);
        activity.startActivity(intent);
    }

    private int roomId;
    private String scheduleId;
    private DiscussGroupBean discussGroupBean;

    private boolean enableVideo, muteMicrophone = false;

    private boolean isInitialized;

    private DiscussGroupMemberAdapter discussGroupMemberAdapter;

    @Override
    protected void onBeforeSetContentLayout() {
        super.onBeforeSetContentLayout();
        StatusBarUtils.setStatusTextColor(this, false);
        //应用运行时，保持屏幕高亮，不锁屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    protected void configIntentValue() {
        Intent intent = getIntent();
        if (intent != null) {
            roomId = getIntent().getIntExtra("ROOM_ID", 0);
            scheduleId = getIntent().getStringExtra("SCHEDULE_ID");
        }
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_discuss_group;
    }

    @Override
    protected void initViews() {
        mDataBinding.ivOnline.setColorFilter(Color.WHITE);
        mDataBinding.ivOffline.setColorFilter(Color.WHITE);
        mDataBinding.ivCamera.setColorFilter(Color.WHITE);
        mDataBinding.ivMic.setColorFilter(Color.WHITE);
        mDataBinding.ivMessage.setColorFilter(Color.WHITE);

        mDataBinding.trcVideoView.setUserId(UserManager.getInstance().uid);

        mDataBinding.layoutCamera.setOnClickListener(this);
        mDataBinding.layoutMic.setOnClickListener(this);
        mDataBinding.layoutOffline.setOnClickListener(this);
        mDataBinding.layoutOnline.setOnClickListener(this);
        mDataBinding.layoutMessage.setOnClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (mPresenter != null) {
            mPresenter.getDiscussGroupDetailData(roomId, scheduleId);
        }
        MyCountDownTimer.getInstance().start();
    }

    @Override
    protected DiscussGroupPresenter getPresenter() {
        return new DiscussGroupPresenter();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mDataBinding.layoutOnline) {
            if (mPresenter != null) {
                mPresenter.checkOnlineMemberStatus(discussGroupBean.SubRoomID);
                mDataBinding.layoutOnline.setEnabled(false);
            }
        } else if (view == mDataBinding.layoutOffline) {
            TICManager.getInstance().getTRTCCloud().stopLocalPreview();
            TICManager.getInstance().getTRTCCloud().stopLocalAudio();
            onEnableVideo(true);
        } else if (view == mDataBinding.layoutCamera) {
            onEnableVideo(false);
        } else if (view == mDataBinding.layoutMic) {
            onMuteMicrophone();
        } else if (view == mDataBinding.layoutMessage) {
            mDataBinding.viewMessage.setVisibility(View.GONE);
            if (mPresenter != null) {
                mPresenter.showChatMessageDialog(getSupportFragmentManager());
                mDataBinding.layoutMessage.setEnabled(false);
            }
        }
    }


    @Override
    public void configDiscussGroupDetailData(DiscussGroupTempRoomBean data) {
        if (data == null) {
            mDataBinding.mcdtvCountDown.setText("倒计时：00:00:00");
        } else {
            if (data.subRoom != null) {
                this.discussGroupBean = data.subRoom;
                mDataBinding.tvDescription.setText(discussGroupBean.DiscussionSubject);
                mDataBinding.tvDescription.setMovementMethod(ScrollingMovementMethod.getInstance());
                long globalEndMilliSeconds = System.currentTimeMillis() + discussGroupBean.DiscussionRemainSec * 1000;
                mDataBinding.mcdtvCountDown.setEndMilliSeconds("倒计时：%s", globalEndMilliSeconds, new MyCountDownTextView.CountDownListener() {
                    @Override
                    public void onTick(long leftMilliseconds) {
                        if (leftMilliseconds <= 0) {
                            mPresenter.showExitDialog(DiscussGroupActivity.this, "讨论时间到了 需要退出讨论回到主讲课堂");
                        }
                    }
                });
                // 加入房间
                if (mPresenter != null) {
                    mPresenter.joinDiscussGroup(roomId);
                    mPresenter.getMemberByUserId(discussGroupBean.CoachUid);
                }
            }
            if (data.members != null) {
                List<BasicUserInfoBean> userBeanList = mPresenter.formatUserBeanList(data.members);
                configOnlineMemberList(userBeanList);
            }
        }
    }

    @Override
    public void onJoinDiscussGroupCallback(boolean isSuccess) {
        if (isSuccess) {
            mDataBinding.trcVideoView.onRoomEnter();
            // 检查权限
            checkCameraAndMicPermission();
        } else {
            LiveClassroomActivity.start(this);
            finishDelay();
        }
    }

    /**
     * 检测权限
     */
    private void checkCameraAndMicPermission() {
        if (MPermission.hasPermissions(this, permissionList)) {
            initTRTCloud();
        } else {
            MPermission.with(this).permissions(permissionList).setRequestCode(Constants.BASIC_PERMISSION_REQUEST_CODE).request();
        }
    }

    @OnMPermissionGranted(Constants.BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
        initTRTCloud();
    }


    @OnMPermissionDenied(Constants.BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(Constants.BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionDenied() {
        ToastUtil.getInstance().show("授权失败");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 初始化腾讯直播
     */
    private void initTRTCloud() {
        if (isInitialized) {
            //开始本地视频图像
            enableVideo = true;
            startLocalVideo(true, true);
            //开始音频
            muteMicrophone = false;
            TICManager.getInstance().getTRTCCloud().startLocalAudio();
            //TODO:开启本地音频采集
            //AudioRecordManager.getInstance().startRecord();
        } else {
            TICManager.getInstance().addEventListener(this);
            TICManager.getInstance().addIMStatusListener(this);
            TICManager.getInstance().addIMMessageListener(this);
            isInitialized = true;
        }
    }


    @Override
    public void onQuitDiscussGroupCallback(boolean isSuccess) {
        TICManager.getInstance().getTRTCCloud().stopLocalPreview();
        TICManager.getInstance().getTRTCCloud().stopLocalAudio();
        TICManager.getInstance().removeEventListener(this);
        TICManager.getInstance().removeIMStatusListener(this);
        LiveClassroomActivity.start(this);
        finishDelay();
    }


    @Override
    public void configOnlineMemberList(List<BasicUserInfoBean> userBeanList) {
        if (discussGroupMemberAdapter == null) {
            mDataBinding.recyclerViewMember.setLayoutManager(new MyLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
            discussGroupMemberAdapter = new DiscussGroupMemberAdapter();
            mDataBinding.recyclerViewMember.setAdapter(discussGroupMemberAdapter);
        }
        discussGroupMemberAdapter.setNewData(userBeanList);
    }

    @Override
    public void checkHasMemberIsSpeakingCallback(Integer data) {
        if (data != null && data <= 0) {
            if (MPermission.hasPermissions(this, permissionList)) {
                initTRTCloud();
            } else {
                MPermission.with(this).permissions(permissionList).setRequestCode(Constants.BASIC_PERMISSION_REQUEST_CODE).request();
            }
        } else {
            showToast("当前已有用户抢到麦了， 请等会再试");
        }
        mDataBinding.layoutOnline.setEnabled(true);
    }

    @Override
    public void onDialogDismiss(DialogFragment dialog) {
        mDataBinding.layoutMessage.setEnabled(true);
    }

    @Override
    public void oUpdateMemberSpeakingStatusCallback(boolean isSuccess) {
        if (isSuccess) {
        }
        mDataBinding.layoutOnline.setEnabled(true);
        mDataBinding.layoutOffline.setEnabled(true);
    }

    /**
     * 开启本地视频推流
     *
     * @param enable
     * @param isNeedUpdateStatus
     */
    private void startLocalVideo(boolean enable, boolean isNeedUpdateStatus) {
        TXCloudVideoView localVideoView = mDataBinding.trcVideoView.getCloudVideoViewByUseId(UserManager.getInstance().uid);
        if (localVideoView == null) {
            localVideoView = mDataBinding.trcVideoView.getFreeCloudVideoView();
        }
        localVideoView.setUserId(UserManager.getInstance().uid);
        localVideoView.setVisibility(View.VISIBLE);
        if (enable) {
            TICManager.getInstance().getTRTCCloud().setLocalViewFillMode(TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FILL);
            TICManager.getInstance().getTRTCCloud().startLocalPreview(true, localVideoView);
        } else {
            TICManager.getInstance().getTRTCCloud().stopLocalPreview();
        }
        if (isNeedUpdateStatus) {
            mDataBinding.layoutNoSpeaking.setVisibility(enable ? View.GONE : View.VISIBLE);
            configOperationButton(enable);
            if (mPresenter != null) {
                mPresenter.UpdateMemberSpeakingStatus(roomId, UserManager.getInstance().uid, enable);
                mPresenter.setMemberSpeakingStatus(UserManager.getInstance().uid, enable);
            }
        }
    }

    private void configOperationButton(boolean available) {
        if (available) {
            long singleEndMilliSeconds = System.currentTimeMillis() + 120 * 1000;
            mDataBinding.mcdtvCountDownSingle.setEndMilliSeconds("倒计时：%s", singleEndMilliSeconds, new MyCountDownTextView.CountDownListener() {
                @Override
                public void onTick(long leftMilliseconds) {
                    if (leftMilliseconds <= 0) {
                        mDataBinding.layoutOffline.performClick();
                    }
                }
            });
            mDataBinding.mcdtvCountDownSingle.setVisibility(View.VISIBLE);
            mDataBinding.layoutOnline.setVisibility(available ? View.GONE : View.VISIBLE);
            mDataBinding.layoutOffline.setVisibility(available ? View.VISIBLE : View.GONE);
            mDataBinding.layoutCamera.setVisibility(available ? View.VISIBLE : View.GONE);
            mDataBinding.layoutMic.setVisibility(available ? View.VISIBLE : View.GONE);
        } else {
            mDataBinding.mcdtvCountDownSingle.setEndMilliSeconds("倒计时：%s", 0, null);
            mDataBinding.mcdtvCountDownSingle.setVisibility(View.GONE);
            mDataBinding.layoutOnline.setVisibility(View.VISIBLE);
            mDataBinding.layoutOffline.setVisibility(View.GONE);
            mDataBinding.layoutCamera.setVisibility(View.GONE);
            mDataBinding.layoutMic.setVisibility(View.GONE);
        }
    }


    /**
     * 开启/关闭视频上行
     */
    private void onEnableVideo(boolean isNeedUpdateStatus) {
        enableVideo = !enableVideo;
        startLocalVideo(enableVideo, isNeedUpdateStatus);
        mDataBinding.trcVideoView.updateVideoStatus(UserManager.getInstance().uid, enableVideo);
        if (!isNeedUpdateStatus) {
            mDataBinding.ivCamera.setImageResource(enableVideo ? R.mipmap.icon_camera_disable : R.mipmap.icon_camera_enable);
        }
    }

    /**
     * 开启/关闭音频上行
     */
    private void onMuteMicrophone() {
        muteMicrophone = !muteMicrophone;
        TICManager.getInstance().getTRTCCloud().muteLocalAudio(muteMicrophone);
        mDataBinding.ivMic.setImageResource(muteMicrophone ? R.mipmap.icon_microphone_enable : R.mipmap.icon_microphone_disable);
    }


    @Override
    public void onTICReceiveTextMessage(String userId, String content, TIMMessage message) {
        if (mPresenter != null) {
            mPresenter.saveChatMessage(userId, true, content, "Receive", message);
        }
        if (mDataBinding.viewMessage.getVisibility() == View.GONE) {
            mDataBinding.viewMessage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onTICReceiveCustomMessage(String fromUserId, byte[] data) {
        MyLogger.d(TAG, "onTICReceiveCustomMessage");
    }

    @Override
    public void onTICReceiveGroupTextMessage(String fromUserId, String text, TIMMessage message) {
        if (mPresenter != null) {
            mPresenter.saveChatMessage(fromUserId, false, text, "Receive", message);
        }
        if (mDataBinding.viewMessage.getVisibility() == View.GONE) {
            mDataBinding.viewMessage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onTICReceiveGroupCustomMessage(String fromUserId, byte[] data) {
        MyLogger.d(TAG, "onTICReceiveGroupCustomMessage");
    }

    @Override
    public void onTICReceiveMessage(TIMMessage message) {
        MyLogger.d(TAG, "onTICReceiveMessage");
    }

    @Override
    public void onTICForceOffline() {
        showToast("您已被踢下线，请检查后重新登录");
        finishDelay();
    }

    @Override
    public void onTICUserSigExpired() {
        showToast("用户签名已过期！");
        finishDelay();
    }

    private String linkedUserId;

    @Override
    public void onTICUserVideoAvailable(String userId, boolean available) {
        MyLogger.d(TAG, "onTICUserVideoAvailable");
        TXCloudVideoView cloudVideoViewByUseId = mDataBinding.trcVideoView.getCloudVideoViewByUseId(UserManager.getInstance().uid);
        if (cloudVideoViewByUseId != null) {
            cloudVideoViewByUseId.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(linkedUserId)) {
            TICManager.getInstance().getTRTCCloud().stopRemoteView(linkedUserId);
            mDataBinding.trcVideoView.onMemberLeave(linkedUserId);
        }
        // 设置remoteView
        configRemoteView(userId, available);
        // 设置当前连麦的userId
        linkedUserId = userId;
        if (mPresenter != null) {
            mPresenter.setMemberSpeakingStatus(linkedUserId, available);
        }
        configOperationButton(false);
    }

    @Override
    public void onTICUserSubStreamAvailable(String userId, boolean available) {
        if (available) {
            final TXCloudVideoView renderView = mDataBinding.trcVideoView.onMemberEnter(userId);
            if (renderView != null) {
                renderView.setUserId(userId);
                TICManager.getInstance().getTRTCCloud().setRemoteViewFillMode(userId, TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FIT);
                TICManager.getInstance().getTRTCCloud().startRemoteSubStreamView(userId, renderView);
            }
        } else {
            TICManager.getInstance().getTRTCCloud().stopRemoteSubStreamView(userId);
            mDataBinding.trcVideoView.onMemberLeave(userId);
        }
    }

    @Override
    public void onTICUserAudioAvailable(String userId, boolean available) {
        MyLogger.d(TAG, "onTICUserAudioAvailable");
        if (available) {
            final TXCloudVideoView renderView = mDataBinding.trcVideoView.onMemberEnter(userId);
            if (renderView != null) {
                renderView.setVisibility(View.VISIBLE);
            }
        }
        BasicUserInfoBean memberByUserId = mPresenter.getMemberByUserId(userId);
        ImageLoader.getInstance().displayImage(memberByUserId.LocalAvatar, mDataBinding.ivUserHeader);
        mDataBinding.ivUserHeader.setVisibility(View.VISIBLE);
    }


    @Override
    public void onTICMemberJoin(List<String> userList) {
        MyLogger.d(TAG, "onTICMemberJoin" + userList.toString());
        if (mPresenter != null && !userList.isEmpty()) {
            mPresenter.setMemberJoin(userList);
        }
    }

    @Override
    public void onTICMemberQuit(List<String> userList) {
        MyLogger.d(TAG, "onTICMemberQuit" + userList.toString());
        if (mPresenter != null && !userList.isEmpty()) {
            mPresenter.setMemberQuit(userList);
        }
    }

    @Override
    public void onTICVideoDisconnect(int errCode, String errMsg) {
        MyLogger.d(TAG, "onTICVideoDisconnect" + errMsg);
    }

    @Override
    public void onTICClassroomDestroy() {
        showToast("课堂已销毁");
        finishDelay();
    }

    @Override
    public void onTICSendOfflineRecordInfo(int code, String desc) {
        MyLogger.d(TAG, "同步录制信息， code = " + code);
    }

    @Override
    public void onUserVoiceVolume(ArrayList<TRTCCloudDef.TRTCVolumeInfo> userVolumes, int totalVolume) {
        mDataBinding.trcVideoView.resetAudioVolume();
        for (int i = 0; i < userVolumes.size(); i++) {
            MyLogger.d(TAG, "" + userVolumes.get(i).volume);
            mDataBinding.trcVideoView.updateAudioVolume(userVolumes.get(i).userId, userVolumes.get(i).volume);
        }
    }

    @Override
    public void onFirstVideoFrame(String userId, int streamType, int width, int height) {

    }

    @Override
    public void onSendFirstLocalVideoFrame(int streamType) {

    }

    @Override
    public void onNetworkQuality(TRTCCloudDef.TRTCQuality localQuality, ArrayList<TRTCCloudDef.TRTCQuality> remoteQuality) {
        mDataBinding.trcVideoView.updateNetworkQuality(localQuality.userId, localQuality.quality);
        if (localQuality.quality > 5) {
            showToast("当前你的网络信号差");
        }
        for (TRTCCloudDef.TRTCQuality qualityInfo : remoteQuality) {
            mDataBinding.trcVideoView.updateNetworkQuality(qualityInfo.userId, qualityInfo.quality);
            if (qualityInfo.quality > 5) {
                showToast("当前对方的网络信号差");
            }
        }
    }

    @Override
    public void onCapturedAudioFrame(TRTCCloudDef.TRTCAudioFrame trtcAudioFrame) {

    }

    private void configRemoteView(String userId, boolean available) {
        if (available) {
            TXCloudVideoView renderView = mDataBinding.trcVideoView.onMemberEnter(userId);
            if (renderView != null) {
                renderView.setUserId(userId);
                TICManager.getInstance().getTRTCCloud().setRemoteViewFillMode(userId, TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FILL);
                TICManager.getInstance().getTRTCCloud().startRemoteView(userId, renderView);
                int index = (int) renderView.getTag(com.tencent.ticsdk.R.string.str_tag_pos);
                mDataBinding.trcVideoView.makeFullVideoView(index);
            }
        } else {
            TICManager.getInstance().getTRTCCloud().stopRemoteView(userId);
            mDataBinding.trcVideoView.onMemberLeave(userId);
        }
        mDataBinding.layoutNoSpeaking.setVisibility(available ? View.GONE : View.VISIBLE);
        mDataBinding.trcVideoView.updateVideoStatus(userId, available);
    }

    @Override
    public void onBackPressed() {
//        if (mPresenter != null) {
//            if (System.currentTimeMillis() > globalEndMilliSeconds) {
//                mPresenter.quitDiscussGroup();
//            } else {
//                mPresenter.showExitDialog(this, "确定要退出讨论回到主讲课堂吗？");
//            }
//        } else {
//            LiveClassroomActivity.start(this);
//            finishDelay();
//        }
    }
}
